package com.zoe.onelink.logging.trace.zipkin.interceptor;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-10-10
 */
public class ZipkinRestTemplateGZipInterceptor implements ClientHttpRequestInterceptor {

    public static final String CONTENT_ENCODING_HEADER_NAME = "Content-Encoding";
    public static final String CONTENT_ENCODING_TYPE = "gzip";

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        request.getHeaders().add(CONTENT_ENCODING_HEADER_NAME, CONTENT_ENCODING_TYPE);
        ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
        try (GZIPOutputStream compressor = new GZIPOutputStream(gzipped)) {
            compressor.write(body);
        }
        return execution.execute(request, gzipped.toByteArray());
    }

}
